#! /usr/bin/env python3
import os
from webPathUtil import fromPathToHtml


def get_rec_dict(dict_ins, result_list=list()):
    for key in dict_ins:
        if ".md" in key:
            result_list.append(key)
        value = dict_ins[key]
        if isinstance(value, dict):
            result_list = get_rec_dict(dict_ins=value, result_list=result_list)
    return result_list


def get_main_html(body):
    head = "Content-type:text/html\n\n"
    with open("html/main.web", "r", encoding="UTF-8") as f:
        constent = f.read()
        constent = constent.format(main=body, sel_part="")
        return head + constent


def get_file_cor_time(path, lab='st_mtime'):
    if os.path.exists(path):
        time = eval('os.stat(path).' + lab)
        return time
    else:
        raise Exception


def main(note_path, except_list, execf):
    last = list()
    result = fromPathToHtml.file_tree(note_path, except_list)
    last = get_rec_dict(result, last)
    cpm_dict = dict()
    last_list = list()
    for li in last:
        time = get_file_cor_time(os.path.join(note_path, li))
        cpm_dict.setdefault(int(time * 100), li)
    temp_list = cpm_dict.keys()
    temp_list = sorted(temp_list, reverse=True)
    for key in temp_list:
        last_list.append(cpm_dict[key])
    last_str = "<h2>最新修改的文件：</h2><br></br>\n<ul>"
    for li in last_list[:19]:
        last_str += "<li><a href=\"%s\" target=\"_self\">%s</a></li><br>\n" % (execf + "?file=" + li, li.split("/")[-1])
    last_str += "</ul>"
    html = get_main_html(last_str)
    print(html)
